package com.jinly.ryder.database.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinly.ryder.account.web.utils.AuthUtil;
import com.jinly.ryder.common.auth.LoginContent;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import com.jinly.ryder.database.service.SqlTaskService;
import com.jinly.ryder.database.service.model.SqlTask;
import com.jinly.ryder.database.web.mapping.SqlTaskItemVOMapping;
import com.jinly.ryder.database.web.mapping.SqlTaskVOMapping;
import com.jinly.ryder.database.web.vo.SqlTaskItemVO;
import com.jinly.ryder.database.web.vo.SqlTaskVO;
import com.jinly.ryder.manage.service.DatabaseInstanceService;
import com.jinly.ryder.manage.service.model.DatabaseInstance;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("sqlTask")
@RequiredArgsConstructor
public class SqlTaskController {

    private final SqlTaskService sqlTaskService;
    private final SqlTaskItemVOMapping sqlTaskItemVOMapping;
    private final SqlTaskVOMapping sqlTaskVOMapping;

    private final DatabaseInstanceService databaseInstanceService;

    @GetMapping("page")
    public Page<SqlTaskVO> sqlTaskVOPage(Long current, Long size, SqlTaskVO queryVO) {
        SqlTask query = sqlTaskVOMapping.toModel(queryVO);
        query.setApplyUserId(LoginContent.getUserId());
        return sqlTaskVOMapping.toVOPage(sqlTaskService.sqlTaskPage(new Page(current, size), query));
    }

    @GetMapping("/{taskId}")
    public SqlTaskVO getSqlTask(@PathVariable Long taskId) {
        SqlTaskVO sqlTaskVO = sqlTaskVOMapping.toVo(sqlTaskService.getSqlTask(taskId, false));
        if (sqlTaskVO != null) {
            sqlTaskVO.setItemList(sqlTaskItemVOMapping.toVoList(sqlTaskService.queryItemList(sqlTaskVO.getId())));
        }
        return sqlTaskVO;
    }

    @PutMapping("checkSql")
    public List<SqlTaskItemVO> checkSql(@RequestBody String sqlText) {
        return sqlTaskItemVOMapping.toVoList(sqlTaskService.parseSqlToItem(sqlText));
    }

    @PutMapping("exec/{taskId}")
    public void execTask(@PathVariable Long taskId) {
        SqlTask sqlTask = sqlTaskService.getSqlTask(taskId, false);
        if (sqlTask != null && Objects.equals(sqlTask.getApplyUserId(), LoginContent.getUserId())) {
            DatabaseInstance instance = databaseInstanceService.get(sqlTask.getDatabaseId());
            Assert.notNull(instance, "实例不存在");
            AuthUtil.check(AuthType.APP, instance.getAppName(), AuthRole.DEVELOPER);
            sqlTaskService.execSqlTask(sqlTask, instance);
        }
    }
}
